package com.jushu.storbox.util.identity;

import java.io.FileInputStream;
import java.security.MessageDigest;

public class FileMD5Identity extends AbsFileIdentity {
	
	public FileMD5Identity(String filePath) {
		super(filePath);
	}
	
	public FileMD5Identity(String filePath, IidentityCallback callback) {
		super(filePath, callback);
	}

	private String computeMD5() throws Exception{
		FileInputStream fis = null;
		try {
			byte[] tempBuffer = new byte[1024 * 64];
			fis = new FileInputStream(innerFile);
			MessageDigest messageDigest = MessageDigest.getInstance("MD5");
			int len = -1;
			long currentProgress = 0;
			long oldProgress = 0;
			long progress = 0;
			while((len = fis.read(tempBuffer)) != -1){
				messageDigest.update(tempBuffer, 0, len);
				currentProgress = len;
				oldProgress = currentProgress * 100 / innerFile.length();
				if ( progress != oldProgress) {
					progress = oldProgress;
					IdentityCallback.onProgress((int) progress,
							(long) currentProgress, innerFile.length());// onProgress
				}
			}
			identity = bytes2String(messageDigest.digest());
			tempBuffer = null;
		} finally {
			if(fis != null) {
				fis.close();
				fis = null;
			}
		}
		return identity;
	}

	@Override
	protected String doComputeIdentity() throws Exception{
		identity = computeMD5();
		return identity;
	}
}
